package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.LoginService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    //登录获取openid
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    //获取token
    private static final String TOKEN_URL  = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL  = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;
    @Override
    public String getOpenId(String  code) {

        //发送请求获取id
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", appSecret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String string = HttpUtil.get(REQUEST_URL, params);
        JSONObject result = JSONUtil.parseObj(string);
        String openId = result.getStr("openid");
        return openId;
    }

    @Override
    public String getPhone(String phoneCode) {
        //调用getToken方法
        String token = getToken();
        String phoneUrl = PHONE_REQUEST_URL + token;
        Map<String, Object> params = new HashMap<>();
        params.put("code",phoneCode);
        String string = HttpUtil.post(phoneUrl, JSONUtil.toJsonStr( params));
        JSONObject jsonObject = JSONUtil.parseObj(string);
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");

    }

    public String getToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", appSecret);
        String result = HttpUtil.get(TOKEN_URL, params);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("access_token");
    }

}
